package com.unione.unione_network.tcp_socket

import java.io.IOException
import java.io.InputStream


/**
 * 定长的粘包处理
 * 例：协议规定每次包的长度为 16
 */
class StaticLenStickPackageHelper(private var stackLen: Int = 32) : AbsStickPackageHelper {


    override fun execute(inputStream: InputStream): ByteArray? {
        var count = 0
        var len: Int = -1
        var temp: Byte
        val result = ByteArray(stackLen)

        try {
            while (count < stackLen && (inputStream.read().also { len = it }) != -1) {
                temp = len.toByte()
                result[count] = temp
                count++
            }
            if (len == -1) {
                return null
            }
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }

        return result.copyOf(count)
    }
}